import 'dart:convert';

import 'package:dio/dio.dart' as Resp;
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:get/get.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:ty_smart_watch/bean/login_bean.dart';
import 'package:ty_smart_watch/utils/Log.dart';
import 'package:ty_smart_watch/utils/http_util.dart';

import '../../common/common.dart';
import '../../route/routes.dart';

/// 用户注册页
class PasswordLoginPage extends StatefulWidget {
  const PasswordLoginPage({super.key});

  @override
  State<PasswordLoginPage> createState() => _PasswordLoginPageState();
}

class _PasswordLoginPageState extends State<PasswordLoginPage> {
  bool _pwdLoginEnable = false;
  final TextEditingController _phoneTextController = TextEditingController();
  final TextEditingController _pwdTextController = TextEditingController();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomInset: false,
      appBar: AppBar(
        leading: IconButton(
          icon: const Icon(Icons.arrow_back_ios),
          onPressed: () {
            Get.back();
          },
        ),
        // automaticallyImplyLeading: false,
      ),
      body: Container(
        margin: const EdgeInsets.symmetric(horizontal: 20),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            const Text(
              "密码登录",
              style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold, color: Color(0xFF0C0C0C)),
            ),
            const SizedBox(height: 20),
            //手机号
            Container(
              decoration: BoxDecoration(
                border: Border.all(color: const Color(0xFF7A7A7A), width: 1),
                //圆角半径
                borderRadius: const BorderRadius.all(Radius.circular(50.0)),
                //背景色
                color: const Color(0xFFFFFBFF),
              ),
              child: Row(
                // crossAxisAlignment: CrossAxisAlignment.stretch,
                children: [
                  Expanded(
                    child: Padding(
                      padding: const EdgeInsets.symmetric(horizontal: 10.0),
                      child: TextField(
                        controller: _phoneTextController,
                        onChanged: (v) {
                          _checkRegisterEnable();
                        },
                        decoration: const InputDecoration(
                            hintText: "请输入手机号",
                            hintStyle: TextStyle(
                              color: Color(0xFF969696),
                            ),
                            border: InputBorder.none),
                        keyboardType: TextInputType.number,
                        inputFormatters: [
                          FilteringTextInputFormatter.digitsOnly, //数字，只能是整数
                        ],
                        maxLines: 1,
                      ),
                    ),
                  ),
                  Container(
                    height: 24,
                    width: 0.5, // 设置竖线的宽度
                    color: const Color(0xFF969696), // 设置竖线的颜色
                  ),
                  const SizedBox(width: 6),
                  const Text(
                    "国家/地区",
                    style: TextStyle(
                      color: Color(0xFF969696),
                    ),
                  ),
                  const SizedBox(width: 10)
                ],
              ),
            ),
            const SizedBox(height: 20),
            //密码输入框
            Container(
              decoration: BoxDecoration(
                border: Border.all(color: const Color(0xFF7A7A7A), width: 1),
                //圆角半径
                borderRadius: const BorderRadius.all(Radius.circular(50.0)),
                //背景色
                color: const Color(0xFFFFFBFF),
              ),
              child: Padding(
                padding: const EdgeInsets.symmetric(horizontal: 10.0),
                child: TextField(
                  controller: _pwdTextController,
                  onChanged: (v) {
                    _checkRegisterEnable();
                  },
                  decoration: const InputDecoration(
                      hintText: "登录密码",
                      hintStyle: TextStyle(
                        color: Color(0xFF969696),
                      ),
                      border: InputBorder.none),
                  obscureText: true,
                  maxLines: 1,
                ),
              ),
            ),
            const Expanded(child: SizedBox()),
            const SizedBox(height: 30),
            //登录按钮
            GestureDetector(
              onTap: _pwdLoginEnable ? () => _login() : null,
              child: Container(
                height: 50,
                padding: const EdgeInsets.symmetric(vertical: 10),
                decoration: BoxDecoration(
                  //圆角半径
                  borderRadius: const BorderRadius.all(Radius.circular(50.0)),
                  color: _pwdLoginEnable ? const Color(0xFF2A6FE5) : const Color(0xFF80A3DF),
                ),
                child: const Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Text(
                      "登录",
                      style:
                          TextStyle(fontSize: 18, color: Colors.white, fontWeight: FontWeight.bold),
                    ),
                  ],
                ),
              ),
            ),
            const SizedBox(height: 60),
          ],
        ),
      ),
    );
  }

  _checkRegisterEnable() {
    if (_phoneTextController.text.isEmpty || _pwdTextController.text.isEmpty) {
      setState(() {
        _pwdLoginEnable = false;
      });
    } else {
      setState(() {
        _pwdLoginEnable = true;
      });
    }
  }

  ///密码登录
  _login() async {
    Log.d("登录 >>  ${_phoneTextController.text}  ::  ${_pwdTextController.text} ");
    SmartDialog.showLoading(msg: "登录中...");
    SharedPreferences prefs = await SharedPreferences.getInstance();
    var dio = HttpUtil.instance?.serviceDio();
    dio.options.headers['tenant-id'] = "1";
    Map<String, dynamic> data = {
      'mobile': _phoneTextController.text,
      'password': _pwdTextController.text,
    };
    Resp.Response response = await dio.post("/member/auth/login", data: data);
    print("登录结果 ： $response");
    try {
      Map<String, dynamic> loginMap = jsonDecode(response.toString());
      LoginBean loginBean = LoginBean.fromJson(loginMap);

      if (loginBean.code == 0) {
        //登录成功
        prefs.setInt(SP_USER_ID, loginBean.data?.userId ?? -1);
        prefs.setString(SP_ACCESS_TOKEN, loginBean.data?.accessToken ?? "");
        prefs.setString(SP_REFRESH_TOKEN, loginBean.data?.refreshToken ?? "");
        Get.offAllNamed(Routes.initial);
      } else {
        SmartDialog.showToast(loginBean.msg ?? "登录失败");
      }
    } catch (e) {
      print("e: $e");
    } finally {
      SmartDialog.dismiss(status: SmartStatus.loading);
    }
  }
}
